import React, { useState, useCallback } from 'react';
import { Player, Position, BOARD_SIZE, STAR_POINTS } from '../types/game';
import { Piece, HoverPiece } from './Piece';

interface BoardProps {
  board: Player[][];
  onCellClick: (row: number, col: number) => void;
  lastMove: Position | null;
  winningLine: Position[];
  disabled?: boolean;
  isAIThinking?: boolean;
}

export const Board: React.FC<BoardProps> = ({
  board,
  onCellClick,
  lastMove,
  winningLine,
  disabled = false,
  isAIThinking = false,
}) => {
  const [hoveredCell, setHoveredCell] = useState<Position | null>(null);
  const [currentPlayer, setCurrentPlayer] = useState<Player>('black');

  const handleCellClick = useCallback((row: number, col: number) => {
    if (disabled || isAIThinking) return;
    if (board[row][col] !== null) return;
    
    onCellClick(row, col);
  }, [disabled, isAIThinking, board, onCellClick]);

  const handleCellHover = useCallback((row: number, col: number) => {
    if (disabled || isAIThinking) return;
    if (board[row][col] !== null) return;
    
    setHoveredCell({ row, col });
  }, [disabled, isAIThinking, board]);

  const handleCellLeave = useCallback(() => {
    setHoveredCell(null);
  }, []);

  const isWinningPosition = (row: number, col: number): boolean => {
    return winningLine.some(pos => pos.row === row && pos.col === col);
  };

  const isLastMove = (row: number, col: number): boolean => {
    return lastMove?.row === row && lastMove?.col === col;
  };

  const isStarPoint = (row: number, col: number): boolean => {
    return STAR_POINTS.some(point => point.row === row && point.col === col);
  };

  const boardSize = {
    base: 'min(calc(100vw - 32px), 600px)',
    tablet: '480px',
    desktop: '600px',
  };

  return (
    <div className="flex justify-center items-center p-4">
      <div 
        className={`
          relative rounded-lg shadow-card border-2 border-neutral-300
          ${disabled ? 'opacity-60' : ''}
          transition-opacity duration-normal
        `}
        style={{
          width: boardSize.base,
          height: boardSize.base,
          backgroundColor: '#F5F2E8',
        }}
      >
        {/* 棋盘网格 */}
        <svg 
          className="absolute inset-0 w-full h-full"
          viewBox={`0 0 ${BOARD_SIZE * 40} ${BOARD_SIZE * 40}`}
          preserveAspectRatio="xMidYMid meet"
        >
          {/* 网格线 */}
          {Array.from({ length: BOARD_SIZE }, (_, i) => (
            <g key={`lines-${i}`}>
              {/* 水平线 */}
              <line
                x1="20"
                y1={20 + i * 40}
                x2={BOARD_SIZE * 40 - 20}
                y2={20 + i * 40}
                stroke="#1A1A1A"
                strokeWidth="1.5"
              />
              {/* 垂直线 */}
              <line
                x1={20 + i * 40}
                y1="20"
                x2={20 + i * 40}
                y2={BOARD_SIZE * 40 - 20}
                stroke="#1A1A1A"
                strokeWidth="1.5"
              />
            </g>
          ))}
          
          {/* 星位点 */}
          {STAR_POINTS.map((point, index) => (
            <circle
              key={`star-${index}`}
              cx={20 + point.col * 40}
              cy={20 + point.row * 40}
              r="3"
              fill="#666666"
            />
          ))}
        </svg>

        {/* 棋盘交叉点 */}
        <div className="absolute inset-0" style={{ padding: '20px' }}>
          {board.map((row, rowIndex) =>
            row.map((cell, colIndex) => (
              <div
                key={`${rowIndex}-${colIndex}`}
                className={`
                  absolute cursor-pointer
                  ${!disabled && !isAIThinking && cell === null ? 'hover:bg-primary-50' : ''}
                  ${disabled ? 'cursor-not-allowed' : ''}
                  transition-colors duration-fast
                `}
                style={{
                  left: `${colIndex * 40}px`,
                  top: `${rowIndex * 40}px`,
                  width: '40px',
                  height: '40px',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}
                onClick={() => handleCellClick(rowIndex, colIndex)}
                onMouseEnter={() => handleCellHover(rowIndex, colIndex)}
                onMouseLeave={handleCellLeave}
              >
                {/* 悬停预览棋子 */}
                {hoveredCell?.row === rowIndex && hoveredCell?.col === colIndex && (
                  <HoverPiece player={currentPlayer} />
                )}
                
                {/* 实际棋子 */}
                {cell && (
                  <Piece 
                    player={cell}
                    isWinning={isWinningPosition(rowIndex, colIndex)}
                    className={`
                      ${isLastMove(rowIndex, colIndex) ? 'ring-2 ring-primary-500' : ''}
                      ${isAIThinking ? 'animate-pulse' : ''}
                    `}
                  />
                )}
              </div>
            ))
          )}
        </div>

        {/* AI思考指示器 */}
        {isAIThinking && (
          <div className="absolute inset-0 bg-black bg-opacity-10 flex items-center justify-center rounded-lg">
            <div className="bg-white px-4 py-2 rounded-full shadow-card flex items-center space-x-2">
              <div className="w-2 h-2 bg-primary-500 rounded-full animate-bounce"></div>
              <div className="w-2 h-2 bg-primary-500 rounded-full animate-bounce" style={{ animationDelay: '0.1s' }}></div>
              <div className="w-2 h-2 bg-primary-500 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }}></div>
              <span className="text-sm text-neutral-700 ml-2">AI思考中...</span>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};